<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script>
        var host = window.location.host;
        var userId = parseInt(Math.random() * (999 - 100 + 1) + 100, 10);
        var webSocket = new WebSocket("ws://" + host + "/ws/chat?roomId=1001&userId=" + userId);
        webSocket.onmessage = function (ev) {
            var textArea = document.getElementById("chat_list");
            var history = textArea.value;
            if (history === "") {
                history += ev.data;
            } else {
                history += "\n" + ev.data;
            }
            textArea.value = history;
        };

        webSocket.onopen = function (ev) {
            var textArea = document.getElementById("chat_list");
            textArea.value = "已进入聊天室 1001";
        };

        webSocket.onclose = function (ev) {
            var textArea = document.getElementById("chat_list");
            textArea.value = "用户 " + userId + " 已离开聊天室 1001";
        };

        function sendMessage() {
            var txt = document.getElementById("msg").value;
            webSocket.send(txt);
        }
    </script>
</head>
<body>
<textarea id="chat_list" rows="10" style="width: 220px"></textarea>
<br/>
<input type="text" id="msg"/>
<input type="button" value="发送" id="send" onclick="sendMessage()"/>
</body>
</html>